<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>修改商品</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- form 表单 -->

      <el-form
        :model="editInfo"
        :rules="editInfoRules"
        ref="editInfoRef"
        label-position="top"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editInfo.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="goods_price">
          <el-input type="number" v-model="editInfo.goods_price"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="goods_number">
          <el-input type="number" v-model="editInfo.goods_number"></el-input>
        </el-form-item>

        <el-form-item label="重量" prop="goods_weight">
          <el-input type="number" v-model="editInfo.goods_weight"></el-input>
        </el-form-item>

        <el-form-item label="商品介绍">
          <quill-editor v-model="editInfo.goods_introduce" ref="myQuillEditor">
          </quill-editor>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item label="商品介绍">
          <el-upload
            class="upload-demo"
            :action="uploadurl"
            :headers="headersConfig"
            :on-success="uploadsuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="editInfo.picsFileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          
        </el-form-item>
        
      </el-form>

      <div class="btn_box">
        <el-button type="primary" @click="subEditInfo">提交</el-button>
      </div>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisiable" width="30%">
      <img class="img_pre" :src="picSrc" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { getdata } from "../../network/getdata";
import { uploadUrl } from "../../network/uploadUrl";
import _ from "lodash";
export default {
  name: "edit",
  data() {
    return {
      //表单数据
      editInfo: {},
      //商品表单校验规则
      editInfoRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
      },
      //图片上传请求头的设置
      headersConfig: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片上传的Url
      uploadurl: uploadUrl,
      //图片预览的显示与隐藏
      picDialogVisiable: false,
      //预览图片Url
      picSrc: "",
    };
  },
  methods: {
    //提交编辑数据
    subEditInfo() {
      //先进行表单校验
      this.$refs.editInfoRef.validate((valid) => {
        if(!valid) {
          this.$message.error('数据不能为空')
          return ;
        }

        //数据合法 -- 发起请求
        console.log(this.editInfo)
        // console.log(this.editInfo.picsFileList[0].url.split('uploads')[1])
        const params = {
          goods_name:this.editInfo.goods_name,
          goods_price:this.editInfo.goods_price,
          goods_cat:this.editInfo.goods_cat.split(',')[2],
          goods_number:this.editInfo.goods_number,
          goods_weight:this.editInfo.goods_weight,
          goods_introduce:this.editInfo.goods_introduce,
          pics:this.editInfo.pics,
          attrs:this.editInfo.attrs
        }
        getdata({
          method:'put',
          url:`/goods/${this.editInfo.goods_id}`,
          data:params
        }).then(result => {
          const res = result.data
          if(res.meta.status !== 200) {
            this.$message.error('修改商品失败');
            return ;
          }
          this.$refs.editInfoRef.resetFields();
          this.$router.push('/goods')
        })
      })
    },
    //预览
    handlePreview(file) {
      this.picSrc = file.url;
      this.picDialogVisiable = true;
    },
    //移除图片
    handleRemove(file, fileList) {
      //图片移除
      //根据file查找出 url
      // console.log(file);
      if (file.response.data) {
        const index = this.editInfo.pics.findIndex((item) => {
          item.pic == file.response.data.tmp_path;
        })
        // 根据 index 将图片移除
        this.editInfo.pics.splice(index,1)
        console.log(this.editInfo.pics)
      }
    },
    //图片上传成功的回调
    uploadsuccess(response, file, fileList) {
      // console.log(response)
      // 将图片保存到 pics数组中
      let tempPath = {};
      tempPath.pic = response.data.tmp_path;
      this.editInfo.pics.push(tempPath);
      console.log(this.editInfo.pics);
    },
  },
  created() {
    const paramsData = this.$route.params;
    if (!paramsData) {
      this.$message.error("参数传递失败");
      return;
    }
    // console.log(paramsData);
    //获取成功
    this.editInfo = paramsData;
    //深拷贝一份商品信息
    // let newEditInfo = _.cloneDeep(this.editInfo)
    //对新商品信息中的图片进行处理，用来展示
    let newPics = [];
    // newEditInfo.pics.forEach(item => {
    //     const temp = {}
    //     temp.name = item.pics_id
    //     temp.url = item.pics_sma
    //     newPics.push(temp)
    // });
    // newEditInfo.pics = newPics

    this.editInfo.pics.forEach((item) => {
      const temp = {};
      temp.name = item.pics_id;
      temp.url = item.pics_big_url + "";
      newPics.push(temp);
    });
    this.editInfo.picsFileList = newPics;
    this.editInfo.pics = [];
    console.log(this.editInfo);
  },
};
</script>

<style lang="less" scoped>
.img_pre {
  width: 100%;
}
.btn_box {
  text-align: center;
}
</style>